package utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-6-6
 * Time: 21:27:11
 */
public class Setting {

  public static int addSetting(Connection con, SettingInfo info) throws Exception {
    String sql = "INSERT INTO setting VALUES (NULL, ?, ?)";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setString(1, info.getSname());
    ps.setString(2, info.getSvalue());
    ps.executeUpdate();
    return DBConnection.getLastID(con);
  }

  public static SettingInfo getSetting(Connection con, String sname) throws Exception {
    String sql = "SELECT * FROM setting WHERE sname=?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setString(1, sname);
    ResultSet rs = ps.executeQuery();
    return rs.next() ? rs2Info(rs) : null;
  }

  public static void delSetting(Connection con, String sname) throws Exception {
    String sql = "DELETE FROM setting WHERE sname=?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setString(1, sname);
    ps.executeUpdate();
  }

  private static SettingInfo rs2Info(ResultSet rs) throws SQLException {
    SettingInfo setting = new SettingInfo();
    setting.setSid(rs.getInt("sid"));
    setting.setSname(rs.getString("sname"));
    setting.setSvalue(rs.getString("svalue"));
    return setting;
  }
}
